<template>
  <div class="datasource-management">
    <div class="page-header">
      <h1>数据源管理</h1>
      <p class="page-description">管理所有数据库连接源，重点支持MySQL、PostgreSQL两种主流数据库，同时兼容SQL Server、Oracle等其他数据库类型</p>
    </div>

    <div class="toolbar">
      <el-button type="primary" @click="showAddDialog" :icon="Plus" data-test="create-datasource">
        新增数据源
      </el-button>
      <el-button @click="refreshDataSources" :icon="Refresh" :loading="loading" data-test="refresh-button">
        刷新
      </el-button>
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索数据源名称或类型"
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
      </div>
      <div class="filter-area">
        <el-select v-model="typeFilter" placeholder="数据库类型" style="width: 150px" data-test="type-filter">
          <el-option label="全部" value="" />
          <el-option label="MySQL" value="mysql" />
          <el-option label="PostgreSQL" value="postgresql" />
          <el-option label="SQL Server" value="sqlserver" />
          <el-option label="Oracle" value="oracle" />
        </el-select>
      </div>
    </div>

    <el-table :data="filteredDataSources" v-loading="loading" style="width: 100%" data-test="datasource-table">
      <el-table-column prop="name" label="数据源名称" />
      <el-table-column prop="type" label="数据库类型" />
      <el-table-column prop="host" label="主机地址" />
      <el-table-column prop="port" label="端口" />
      <el-table-column prop="databaseName" label="数据库名" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'connected' ? 'success' : 'danger'">
            {{ scope.row.status === 'connected' ? '已连接' : '未连接' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="testConnection(scope.row)" data-test="test-connection">测试连接</el-button>
          <el-button size="small" type="primary" @click="editDataSource(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteDataSource(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑数据源对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑数据源' : '新增数据源'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入数据源名称" />
        </el-form-item>
        
        <el-form-item label="数据库类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择数据库类型" style="width: 100%">
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="Oracle" value="oracle" />
          </el-select>
        </el-form-item>

        <el-form-item label="主机地址" prop="host">
          <el-input v-model="formData.host" placeholder="请输入主机地址" />
        </el-form-item>

        <el-form-item label="端口" prop="port">
          <el-input-number
            v-model="formData.port"
            :min="1"
            :max="65535"
            style="width: 100%"
            placeholder="请输入端口号"
          />
        </el-form-item>

        <el-form-item label="数据库名" prop="databaseName">
          <el-input v-model="formData.databaseName" placeholder="请输入数据库名称" />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入数据源描述（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="testConnection" :loading="testing">
            测试连接
          </el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  MoreFilled,
  Edit,
  Delete,
  Connection,
  DataBoard,
  Monitor,
  Document,
  Right
} from '@element-plus/icons-vue'
import { dataSourceApi } from '@/api/dataSource'

// 响应式数据
const loading = ref(false)
const testing = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const typeFilter = ref('')
const formRef = ref()

// 数据源列表
const dataSources = ref([])

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  type: '',
  host: '',
  port: null,
  databaseName: '',
  username: '',
  password: '',
  description: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入数据源名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' }
  ],
  databaseName: [
    { required: true, message: '请输入数据库名称', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 计算属性
const filteredDataSources = computed(() => {
  let filtered = dataSources.value
  
  // 按类型过滤
  if (typeFilter.value) {
    filtered = filtered.filter(item => item.type === typeFilter.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      item.host.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      item.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  return filtered
})

// 默认端口映射
const defaultPorts = {
  mysql: 3306,
  postgresql: 5432,
  sqlserver: 1433,
  oracle: 1521
}

// 方法
const getDatabaseTypeText = (type) => {
  const typeMap = {
    mysql: 'MySQL',
    postgresql: 'PostgreSQL',
    sqlserver: 'SQL Server',
    oracle: 'Oracle'
  }
  return typeMap[type] || type
}

const getStatusClass = (status) => {
  return {
    'status-connected': status === 'connected',
    'status-disconnected': status === 'disconnected'
  }
}

const getStatusType = (status) => {
  return status === 'connected' ? 'success' : 'danger'
}

const getStatusText = (status) => {
  return status === 'connected' ? '已连接' : '未连接'
}

const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    type: '',
    host: '',
    port: null,
    databaseName: '',
    username: '',
    password: '',
    description: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleCommand = ({ action, datasource }) => {
  switch (action) {
    case 'test':
      testDataSourceConnection(datasource)
      break
    case 'edit':
      editDataSource(datasource)
      break
    case 'delete':
      deleteDataSource(datasource)
      break
  }
}

const editDataSource = (datasource) => {
  isEdit.value = true
  Object.assign(formData, { ...datasource })
  dialogVisible.value = true
}

const deleteDataSource = async (datasource) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据源 "${datasource.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await dataSourceApi.delete(datasource.id)
    ElMessage.success('数据源删除成功')
    await refreshDataSources()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除数据源失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const testDataSourceConnection = async (datasource) => {
  testing.value = true
  try {
    // 模拟测试连接
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 随机成功或失败
    const success = Math.random() > 0.3
    if (success) {
      ElMessage.success(`数据源 "${datasource.name}" 连接测试成功`)
      // 更新状态
      const ds = dataSources.value.find(d => d.id === datasource.id)
      if (ds) ds.status = 'connected'
    } else {
      ElMessage.error(`数据源 "${datasource.name}" 连接测试失败`)
      const ds = dataSources.value.find(d => d.id === datasource.id)
      if (ds) ds.status = 'disconnected'
    }
  } catch (error) {
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

const testConnection = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    testing.value = true
    
    const result = await dataSourceApi.testConnection(formData)
    if (result.success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error(result.message || '连接测试失败，请检查配置')
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败，请检查网络连接和配置')
  } finally {
    testing.value = false
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      // 更新现有数据源
      await dataSourceApi.update(formData.id, formData)
      ElMessage.success('数据源更新成功')
    } else {
      // 添加新数据源
      await dataSourceApi.create(formData)
      ElMessage.success('数据源添加成功')
    }
    
    dialogVisible.value = false
    resetForm()
    await refreshDataSources()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '更新数据源失败' : '添加数据源失败')
  } finally {
    submitting.value = false
  }
}

const refreshDataSources = async () => {
  loading.value = true
  try {
    const result = await dataSourceApi.getList()
    dataSources.value = result.data || result || []
    ElMessage.success('数据源列表已刷新')
  } catch (error) {
    console.error('刷新数据源列表失败:', error)
    ElMessage.error('刷新失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 监听数据库类型变化，自动设置默认端口
const watchType = () => {
  if (formData.type && !formData.port) {
    formData.port = defaultPorts[formData.type]
  }
}

onMounted(() => {
  refreshDataSources()
})
</script>

<style scoped>
.datasource-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.search-box {
  width: 300px;
}

.datasource-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.datasource-card {
  transition: all 0.3s ease;
}

.datasource-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.datasource-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1f2937;
}

.name-icon {
  color: #3b82f6;
}

.card-content {
  padding-top: 16px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-icon {
  color: #6b7280;
  font-size: 16px;
  width: 16px;
}

.info-label {
  font-weight: 500;
  color: #374151;
  min-width: 50px;
}

.info-value {
  color: #6b7280;
  flex: 1;
}

.status-connected {
  color: #10b981 !important;
}

.status-disconnected {
  color: #ef4444 !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .datasource-grid {
    grid-template-columns: 1fr;
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
}
</style>